package com.zhongshengnetwork.rightbe.common.topgrid.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.topgrid.adapter.DragAdapter;
import com.zhongshengnetwork.rightbe.common.topgrid.adapter.OtherAdapter;
import com.zhongshengnetwork.rightbe.common.topgrid.model.ChannelItem;
import com.zhongshengnetwork.rightbe.common.topgrid.view.DragGrid;
import com.zhongshengnetwork.rightbe.common.topgrid.view.OtherGridView;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangTypeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuLabelInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTListActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTSearchActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WZTGridActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener, AdapterView.OnItemClickListener {

    private TopBarView topbar;

    /** 用户栏目的GRIDVIEW */
    private DragGrid userGridView;
    /** 其它栏目的GRIDVIEW */
    private OtherGridView otherGridView;
    /** 用户栏目对应的适配器，可以拖动 */
    DragAdapter userAdapter;
    /** 其它栏目对应的适配器 */
    OtherAdapter otherAdapter;
    /** 其它栏目列表 */
    ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();
    /** 用户栏目列表 */
    ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();
    //已经选择的id
    ArrayList<String> selectIds = new ArrayList<String>();
    /** 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。 */
    boolean isMove = false;
    private TextView tv_save;
    private TextView my_channel_tip;
    private boolean isSave = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wztgrid);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setText("保存");
        topbar.getRightTextView().setTextSize(18);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveChannel(null);
            }
        });
        initView();
        initData();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    /** 初始化数据*/
    private void initData() {

        //先取平台的（平台营销）
        int orderId = 0;
        String newData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NewWZTChannelDataKey, "");
        String newDataName = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NewWZTChannelNameDataKey, "");
        if(!CommonUtils.isEmpty(newData)){
            List<String> newDatas = CommonUtils.stringToArrayList(newData);
            List<String> newDataNames = CommonUtils.stringToArrayList(newDataName);
            if (newDatas != null && newDatas.size() > 0){
                for (int i = 0; i < newDatas.size(); i++){
                    ChannelItem channelItem = new ChannelItem();
                    channelItem.id = Integer.valueOf(newDatas.get(i));
                    channelItem.name = newDataNames.get(i);
                    channelItem.newItem = 0;
                    channelItem.orderId = orderId;
                    channelItem.isCurrent = false;
                    orderId += 1;
                    channelItem.selected = 1;
                    channelItem.isWZT = true;
                    userChannelList.add(channelItem);
                    selectIds.add(newDatas.get(i));
                }
            }
        }


        //再取用户的
        if (CommonUtils.isLogin() == true){
            String myData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.MyWZTChannelDataKey+CustomApplication.loginModel.getUid(), "");
            if (!CommonUtils.isEmpty(myData)){
                String myDataName = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.MyWZTChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                List<String> myDatas = CommonUtils.stringToArrayList(myData);
                List<String> myDataNames = CommonUtils.stringToArrayList(myDataName);
                if (myDatas != null && myDatas.size() > 0){
                    for (int i = 0; i < myDatas.size(); i++){
                        if (selectIds.contains(myDatas.get(i)) == false){
                            ChannelItem channelItem = new ChannelItem();
                            channelItem.id = Integer.valueOf(myDatas.get(i));
                            channelItem.name = myDataNames.get(i);
                            channelItem.newItem = 0;
                            channelItem.orderId = orderId;
                            channelItem.isCurrent = false;
                            orderId += 1;
                            channelItem.selected = 1;
                            channelItem.isWZT = true;
                            userChannelList.add(channelItem);
                            selectIds.add(myDatas.get(i));
                        }
                    }
                }
            }
        }

        if (userChannelList.size() == 0){
            //上面两个都没有，取系统默认的
            List<String> solidNames = CommonUtils.stringToArrayList(AdvertUtils.DefaultWZTChannelNameData);
            List<String> solidIds = CommonUtils.stringToArrayList(AdvertUtils.DefaultWZTChannelData);
            if (solidIds != null && solidIds.size() > 0){
                for (int i = 0; i < solidIds.size(); i++){
                    ChannelItem channelItem = new ChannelItem();
                    channelItem.id = Integer.valueOf(solidIds.get(i));
                    channelItem.name = solidNames.get(i);
                    channelItem.newItem = 0;
                    channelItem.orderId = orderId;
                    channelItem.isCurrent = false;
                    orderId += 1;
                    channelItem.selected = 1;
                    channelItem.isWZT = true;
                    userChannelList.add(channelItem);
                    selectIds.add(solidIds.get(i));
                }
            }
        }

        final String d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.WZTUserLabelData,"");
        if (!CommonUtils.isEmpty(d)){
            List<WeiShuLabelInfoModel>l = GsonTools.getWeiShuLabelInfoModel(d);
            if (l != null && l.size() > 0){
                for (int i = 0; i < l.size(); i++){
                    WeiShuLabelInfoModel m = l.get(i);
                    if (selectIds.contains(m.getId()+"") == false){
                        ChannelItem channelItem = new ChannelItem();
                        channelItem.id = m.getId();
                        channelItem.name = m.getLabelName();
                        channelItem.newItem = 0;
                        channelItem.orderId = orderId;
                        channelItem.isCurrent = false;
                        orderId += 1;
                        channelItem.selected = 0;
                        channelItem.isWZT = true;
                        otherChannelList.add(channelItem);
                    }
                }
            }
        }


        userAdapter = new DragAdapter(this, userChannelList,userGridView);
        userGridView.setAdapter(userAdapter);
        otherAdapter = new OtherAdapter(this, otherChannelList);
        otherGridView.setAdapter(this.otherAdapter);
        //设置GRIDVIEW的ITEM的点击监听
        otherGridView.setOnItemClickListener(this);
        userGridView.setOnItemClickListener(this);
        userAdapter.setOnDelecteItemListener(new DragAdapter.OnDelecteItemListener() {
            @Override
            public void onDelete(final int position, View v, ViewGroup parent) {
                if (position != 0) {
                    View view = userGridView.getChildAt(position);
                    final ImageView moveImageView = getView(view);
                    if (moveImageView != null) {
                        TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                        final int[] startLocation = new int[2];
                        newTextView.getLocationInWindow(startLocation);
                        final ChannelItem channel = userAdapter.getItem(position);//获取点击的频道内容
                        otherAdapter.setVisible(false);
                        userAdapter.setIsDeleteing(true);
                        //添加到最后一个
                        otherAdapter.addItem(channel);
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                try {
                                    int[] endLocation = new int[2];
                                    //获取终点的坐标
                                    otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                    MoveAnim(moveImageView, startLocation , endLocation, channel,userGridView);
                                    userAdapter.setRemove(position);
                                } catch (Exception localException) {
                                }
                            }
                        }, 50L);
                    }
                }
            }
        });

        userAdapter.setOnStartDragingListener(new DragAdapter.OnStartDragingListener() {
            @Override
            public void onStartDraging() {
                tv_save.setVisibility(View.VISIBLE);
                tv_save.setText("完成");
                my_channel_tip.setText("长按拖动排序");
            }
        });
    }

    /** 初始化布局*/
    private void initView() {

        RelativeLayout top_grid_layout = (RelativeLayout) findViewById(R.id.top_grid_layout);
        top_grid_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        LinearLayout top_grid_bg_layout = (LinearLayout) findViewById(R.id.top_grid_bg_layout);
        top_grid_bg_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        userGridView = (DragGrid) findViewById(R.id.userGridView);
        otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
        tv_save = (TextView) findViewById(R.id.tv_save);
        my_channel_tip = (TextView) findViewById(R.id.my_channel_tip);
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userAdapter.isDeleteing == true){
                    if (isSave == false){
                        saveChannel(null);
                    }
                }else {
                    userAdapter.hideDeleteIcon(false);
                    userAdapter.showDeleteIcon(true);
                    userAdapter.setIsDeleteing(true);
                    userAdapter.notifyDataSetChanged();
                    tv_save.setText("完成");
                    my_channel_tip.setText("长按拖动排序");
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /** GRIDVIEW对应的ITEM点击监听接口  */
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position,long id) {
        //如果点击的时候，之前动画还没结束，那么就让点击事件无效
        if(isMove){
            return;
        }
        switch (parent.getId()) {
            case R.id.userGridView:
                //TODO position为 0的不可以进行任何操作
                if (userAdapter.isDeleteIcon == true){
                    if (position >=0 && userAdapter.channelList.size() > position){
                        ChannelItem item = userAdapter.channelList.get(position);
                        if (item.id > 0){
                            //触发删除
                            if (userAdapter.isDeleteing == false){
                                userAdapter.isDeleteing = true;
                            }
                            final ImageView moveImageView = getView(view);
                            if (moveImageView != null) {
                                TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                                final int[] startLocation = new int[2];
                                newTextView.getLocationInWindow(startLocation);
                                final ChannelItem channel = ((DragAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容
                                otherAdapter.setVisible(false);
                                //添加到最后一个
                                otherAdapter.addItem(channel);
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        try {
                                            int[] endLocation = new int[2];
                                            //获取终点的坐标
                                            otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                            MoveAnim(moveImageView, startLocation , endLocation, channel,userGridView);
                                            userAdapter.setRemove(position);
                                        } catch (Exception localException) {
                                        }
                                    }
                                }, 50L);
                            }
                        }
                    }
                }else {
                    ChannelItem item = userAdapter.channelList.get(position);
                    saveChannel(item);
                }

                break;
            case R.id.otherGridView:
                final ImageView moveImageView = getView(view);
                if (moveImageView != null){
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);
                    final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
                    userAdapter.setVisible(false);
                    //添加到最后一个
                    channel.setNewItem(1);
                    userAdapter.addItem(channel);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                MoveAnim(moveImageView, startLocation , endLocation, channel,otherGridView);
                                otherAdapter.setRemove(position);
                            } catch (Exception localException) {
                            }
                        }
                    }, 50L);
                }
                break;
            default:
                break;
        }
    }
    /**
     * 点击ITEM移动动画
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation,int[] endLocation, final ChannelItem moveChannel,
                          final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    otherAdapter.setVisible(true);
                    otherAdapter.notifyDataSetChanged();
                    userAdapter.remove();
                }else{
                    userAdapter.setVisible(true);
                    userAdapter.notifyDataSetChanged();
                    otherAdapter.remove();
                }
                isMove = false;
            }
        });
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(this);
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取点击的Item的对应View，
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(cache);
        return iv;
    }

    /** 退出时候保存选择后数据库的设置  */
    private void saveChannel(ChannelItem channelItem) {

        if (channelItem != null){
            enterChannel(channelItem.name);
            return;
        }

        //Log.e("TAG", "退出时候保存选择后数据库的设置");
        isSave = true;

        KyLoadingBuilder dialog = new KyLoadingBuilder(WZTGridActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在保存...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();

        userAdapter.hideDeleteIcon(true);
        userAdapter.showDeleteIcon(false);
        userAdapter.setIsDeleteing(false);
        userAdapter.notifyDataSetChanged();

        String value = "";
        String name = "";
        for (int i = 0; i < userAdapter.channelList.size(); i++ ){
            ChannelItem item = userAdapter.channelList.get(i);
            if (item.id > 0){
                Log.e("TAG", "id="+item.id);
                Log.e("TAG", "name="+item.name);
                if (value.length() > 0){
                    value += ",";
                    name += ",";
                }
                value += (item.id+"");
                name += item.name;
            }
        }

        final String saveValue = value;
        final String saveName = name;


        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        }else {
            dialog.dismiss();
            ToastUtil.show(WZTGridActivity.this, "登录过期，请重新登录");
            finish();
            return;
        }
        map.put("dataType", "1");
        map.put("dataId", value);
        String url = "home/menu/user/save.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            ToastUtil.show(WZTGridActivity.this, "保存成功");
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelDataKey+CustomApplication.loginModel.getUid(), saveValue);
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelNameDataKey+CustomApplication.loginModel.getUid(), saveName);
                            Intent intent = new Intent();
                            if (channelItem != null){
                                intent.putExtra("type", channelItem.id);
                            }else {
                                intent.putExtra("type", 0);
                            }
                            intent.putExtra("isSelect", false);
                            setResult(RESULT_OK, intent);
                            finish();
                        }else {
                            if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)) {//登录过期
                                CustomApplication.showTip(commonModel, WZTGridActivity.this);
                                return;
                            }
                            ToastUtil.show(WZTGridActivity.this, commonModel.getMsg());
                            userAdapter.hideDeleteIcon(true);
                            userAdapter.showDeleteIcon(false);
                            userAdapter.setIsDeleteing(false);
                            userAdapter.notifyDataSetChanged();
                            tv_save.setText("编辑");
                            my_channel_tip.setText("点击进入频道");
                            isSave = false;
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        ToastUtil.show(WZTGridActivity.this, "保存失败");
                        userAdapter.hideDeleteIcon(true);
                        userAdapter.showDeleteIcon(false);
                        userAdapter.setIsDeleteing(false);
                        userAdapter.notifyDataSetChanged();
                        tv_save.setText("编辑");
                        my_channel_tip.setText("点击进入频道");
                        isSave = false;
                    }
                });
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    //进入某个频道查看
    private void enterChannel(String title){
        Intent intent = new Intent(WZTGridActivity.this, WZTListActivity.class);
        intent.putExtra("title",title);
        startActivity(intent);
    }

}

